//
//  Tool.m
//  ZuLinProject
//
//  Created by 谭明星 on 2021/12/8.
//


#import "Tool.h"
#import <CommonCrypto/CommonRandom.h>
#define MAXADDRS 32
#ifndef IOS7_OR_LATER
#define IOS7_OR_LATER   ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
#endif
extern char *if_names[MAXADDRS];
extern char *ip_names[MAXADDRS];

extern unsigned long ip_addrs[MAXADDRS];

// Function prototypes

void InitAddresses();
void FreeAddresses();
void GetIPAddresses();
void GetHWAddresses();

/*
 *  IPAddress.c
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/sockio.h>
#include <net/if.h>
#include <errno.h>
#include <net/if_dl.h>
#include <net/ethernet.h>

#define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) > (b) ? (a) : (b))
#define BUFFERSIZE 4000

char *if_names[MAXADDRS];
char *ip_names[MAXADDRS];
char *hw_addrs[MAXADDRS];
unsigned long ip_addrs[MAXADDRS];

static int  nextAddr = 0;

void InitAddresses()
{
    int i;
    for (i=0; i<MAXADDRS; ++i)
    {
        if_names[i] = ip_names[i] = hw_addrs[i] = NULL;
        ip_addrs[i] = 0;
    }
}

void FreeAddresses()
{
    int i;
    for (i=0; i<MAXADDRS; ++i)
    {
        if (if_names[i] != 0) free(if_names[i]);
        if (ip_names[i] != 0) free(ip_names[i]);
        if (hw_addrs[i] != 0) free(hw_addrs[i]);
        ip_addrs[i] = 0;
    }
    
    InitAddresses();
}

void GetIPAddresses()
{
    int                i, len, flags;
    char                buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
    struct ifconf      ifc;
    struct ifreq        *ifr, ifrcopy;
    struct sockaddr_in *sin;
    char temp[80];
    int sockfd;
    for (i=0; i<MAXADDRS; ++i)
    {
        if_names[i] = ip_names[i] = NULL;
        ip_addrs[i] = 0;
    }
    
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket failed");
        return;
    }
    
    ifc.ifc_len = BUFFERSIZE;
    ifc.ifc_buf = buffer;
    if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0)
    {
        perror("ioctl error");
        return;
    }
    lastname[0] = 0;
    for (ptr = buffer; ptr < buffer + ifc.ifc_len; )
    {
        ifr = (struct ifreq *)ptr;
        len = max(sizeof(struct sockaddr), ifr->ifr_addr.sa_len);
        ptr += sizeof(ifr->ifr_name) + len; // for next one in buffer
        if (ifr->ifr_addr.sa_family != AF_INET)
        {
            continue; // ignore if not desired address family
        }
        
        if ((cptr = (char *)strchr(ifr->ifr_name, ':')) != NULL)
        {
            *cptr = 0; // replace colon will null
        }
        
        if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0)
        {
            continue; /* already processed this interface */
        }
        memcpy(lastname, ifr->ifr_name, IFNAMSIZ);
        ifrcopy = *ifr;
        ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy);
        flags = ifrcopy.ifr_flags;
        if ((flags & IFF_UP) == 0)
        {
            continue; // ignore if interface not up
        }
        if_names[nextAddr] = (char *)malloc(strlen(ifr->ifr_name)+1);
        if (if_names[nextAddr] == NULL)
        {
            return;
        }
        
        strcpy(if_names[nextAddr], ifr->ifr_name);
        sin = (struct sockaddr_in *)&ifr->ifr_addr;
        strcpy(temp, inet_ntoa(sin->sin_addr));
        ip_names[nextAddr] = (char *)malloc(strlen(temp)+1);
        
        if (ip_names[nextAddr] == NULL)
        {
            return;
        }
        strcpy(ip_names[nextAddr], temp);
        ip_addrs[nextAddr] = sin->sin_addr.s_addr;
        ++nextAddr;
    }
    
    close(sockfd);
    
}

void GetHWAddresses()
{
    struct ifconf ifc;
    struct ifreq *ifr;
    int i, sockfd;
    char buffer[BUFFERSIZE], *cp, *cplim;
    char temp[80];
    for (i=0; i<MAXADDRS; ++i)
    {
        hw_addrs[i] = NULL;
    }
    
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket failed");
        return;
    }
    
    ifc.ifc_len = BUFFERSIZE;
    ifc.ifc_buf = buffer;
    if (ioctl(sockfd, SIOCGIFCONF, (char *)&ifc) < 0)
    {
        perror("ioctl error");
        close(sockfd);
        return;
    }
    
    ifr = ifc.ifc_req;
    cplim = buffer + ifc.ifc_len;
    for (cp=buffer; cp < cplim; )
    {
        ifr = (struct ifreq *)cp;
        if (ifr->ifr_addr.sa_family == AF_LINK)
        {
            struct sockaddr_dl *sdl = (struct sockaddr_dl *)&ifr->ifr_addr;
            int a,b,c,d,e,f;
            int i;
            strcpy(temp, (char *)ether_ntoa((struct ether_addr*)LLADDR(sdl)));
            sscanf(temp, "%x:%x:%x:%x:%x:%x", &a, &b, &c, &d, &e, &f);
            sprintf(temp, "%02X:%02X:%02X:%02X:%02X:%02X",a,b,c,d,e,f);
            for (i=0; i<MAXADDRS; ++i)
            {
                if ((if_names[i] != NULL) && (strcmp(ifr->ifr_name, if_names[i]) == 0))
                {
                    if (hw_addrs[i] == NULL)
                    {
                        hw_addrs[i] = (char *)malloc(strlen(temp)+1);
                        strcpy(hw_addrs[i], temp);
                        break;
                    }
                }
            }
        }
        cp += sizeof(ifr->ifr_name) + max(sizeof(ifr->ifr_addr), ifr->ifr_addr.sa_len);
    }
    close(sockfd);
}

@implementation Tool


//做ios版本之间的适配
//不同的ios版本,调用不同的方法,实现相同的功能
+(CGSize)sizeOfStr:(NSString *)str andFont:(UIFont *)font andMaxSize:(CGSize)size andLineBreakMode:(NSLineBreakMode)mode
{
    CGSize s;
    if (IOS7_OR_LATER) {
        NSMutableDictionary  *mdic=[NSMutableDictionary dictionary];
        [mdic setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
        [mdic setObject:font forKey:NSFontAttributeName];
        s = [str boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                     attributes:mdic context:nil].size;
    }
    else
    {
        s=[str sizeWithFont:font constrainedToSize:size lineBreakMode:mode];
    }
    return s;
}

+(void) showAlert:(NSString*) message{
    [Tool showAlertWithTitle:@"提示" message:message];
}
+(void) showAlertWithTitle:(NSString *)title message:(NSString*) message{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:title message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}
#pragma mark - 改变图片大小,保持图片的长宽比
+(UIImage*)changeSizeOfImgKeepScale:(UIImage*)sourceImg andMaxLength:(NSInteger)maxWidth andMaxHeight:(NSInteger)maxheight
{
    float width=sourceImg.size.width;
    float height=sourceImg.size.height;
    
    if (width<=maxWidth && height<=maxheight) {
        return sourceImg;
    }
    
    if (width/height<=maxWidth/maxheight) {
        return [Tool changeSizeOfImg:sourceImg andWidth:maxheight/height*width andHeight:maxheight];
    }
    if (width/height>=maxWidth/maxheight) {
        return [Tool changeSizeOfImg:sourceImg andWidth:maxWidth andHeight:maxWidth/width*height];
    }
    return nil;
}

#pragma mark - 改变图片的大小
+(UIImage*)changeSizeOfImg:(UIImage*)sourceImg andWidth:(NSInteger)width andHeight:(NSInteger)height
{
    CGSize size=CGSizeMake(width, height);
    UIGraphicsBeginImageContext(size);
    //获取上下文内容
    CGContextRef ctx= UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(ctx, 0.0, size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    //重绘image
    CGContextDrawImage(ctx,CGRectMake(0.0f, 0.0f, size.width, size.height), sourceImg.CGImage);
    //根据指定的size大小得到新的image
    UIImage* scaled= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaled;
}
#pragma mark - 访问的url,如果里面有中文或者特殊符号,需要先对字符串进行转码
+(NSString*) urlEncodingToUTF8:(NSString*) sourceUrl{
     NSString* encodedString = (NSString*) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)sourceUrl, NULL, NULL, kCFStringEncodingUTF8));
    return encodedString;
}
#pragma mark - 获取设备IP地址
+ (NSString *)deviceIPAdress {
    InitAddresses();
    GetIPAddresses();
    GetHWAddresses();
    return [NSString stringWithFormat:@"%s", ip_names[1]];
}
#pragma mark - 颜色转换 IOS中十六进制的颜色转换为UIColor
+(UIColor*) UIColorFromRGB:(NSUInteger)rgbValue{
    UIColor* color = [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0];
    return color;
}
+(UIColor*) colorWithHexString:(NSString*) color{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
    
}
#pragma mark - 通过文件名获取bundlePath目录的文件
+(NSString *)getBundlePathWithFileName:(NSString *)fileName
{
    return [[NSBundle mainBundle]pathForResource:fileName ofType:nil];
}
#pragma mark - 获取特定字符的range数组
+(NSArray*) getStringRange:(NSString*) string regEx:(NSString*) regEx range:(NSRange) range{
    NSMutableArray* arr = [[NSMutableArray alloc] init];
    [self getStringRange:string regEx:regEx range:range rangeArr:arr];
    return arr;
}
+(NSArray*) getStringRange:(NSString*) string regEx:(NSString*) regEx range:(NSRange) range rangeArr:(NSMutableArray*) arr{
    NSRange rangeTemp = [string rangeOfString:regEx options:NSRegularExpressionSearch range:range];
    if (rangeTemp.length !=0) {
        [arr addObject:[NSValue valueWithRange:rangeTemp]];
        NSRange startRange = NSMakeRange(rangeTemp.length+rangeTemp.location, [string length]-(rangeTemp.length+rangeTemp.location));
        return [self getStringRange:string regEx:regEx range:startRange rangeArr:arr];
    }else{
        return arr;
    }
}
+(NSString *)notRounding:(float)price afterPoint:(int)position{
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *ouncesDecimal;
    NSDecimalNumber *roundedOunces;
    
    ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];
    roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    return [NSString stringWithFormat:@"%@",roundedOunces];
}

+ (void)showAlertTitle:(NSString *)title msg:(NSString *)msg cancelTitle:(NSString *)cancelTitle commitBtnTitle:(NSString *)commitText cancelHandlerBlock:(void(^)(void))cancelHandel commitHandlerBlock:(void (^)(void))Commithandler onVC:(UIViewController *)vc {
    UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        cancelHandel();
    }];
    [alertCtrl addAction:cancelAction];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:commitText style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        Commithandler();
    }];
    [alertCtrl addAction:sureAction];
    
    //修改按钮字体颜色
    [cancelAction setValue:Color333 forKey:@"titleTextColor"];
//    [sureAction setValue:kPassColor forKey:@"titleTextColor"];
    
    [vc presentViewController:alertCtrl animated:YES completion:nil];
    
}


+ (void)showSheetTitle:(NSString *)title
                   msg:(NSString *)msg
           cancelTitle:(NSString *)cancelTitle
           oneBtnTitle:(NSString *)oneText
           twoBtnTitle:(NSString *)twoText
    cancelHandlerBlock:(void (^)(void))cancelHandel oneHandlerBlock:(void (^)(void))oneHandler twoHandlerBlock:(void (^)(void))twoHandler onVC:(UIViewController *)vc{
    
    UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        cancelHandel();
    }];
    [alertCtrl addAction:cancelAction];
    
    UIAlertAction *oneAction = [UIAlertAction actionWithTitle:oneText style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        oneHandler();
    }];
    [alertCtrl addAction:oneAction];
    
    
    if (!StringIsEmpty(twoText)) {
        UIAlertAction *twoAction = [UIAlertAction actionWithTitle:twoText style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            twoHandler();
        }];
        [alertCtrl addAction:twoAction];
    }
    
    
    

    [vc presentViewController:alertCtrl animated:YES completion:nil];
    
    
}

+ (void)showSheetTitle:(NSString *)title
                   msg:(NSString *)msg
           cancelTitle:(NSString *)cancelTitle
           oneBtnTitle:(NSString *)oneText
           twoBtnTitle:(NSString *)twoText
           threeBtnTitle:(NSString *)threeText
    cancelHandlerBlock:(void (^)(void))cancelHandel
       oneHandlerBlock:(void (^)(void))oneHandler
       twoHandlerBlock:(void (^)(void))twoHandler
       threeHandlerBlock:(void (^)(void))threeHandler
                  onVC:(UIViewController *)vc{
    
    UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        cancelHandel();
    }];
    [alertCtrl addAction:cancelAction];
    
    UIAlertAction *oneAction = [UIAlertAction actionWithTitle:oneText style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        oneHandler();
    }];
    [alertCtrl addAction:oneAction];
    
    
    if (!StringIsEmpty(twoText)) {
        UIAlertAction *twoAction = [UIAlertAction actionWithTitle:twoText style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            twoHandler();
        }];
        [alertCtrl addAction:twoAction];
    }
    
    
    if (!StringIsEmpty(threeText)) {
        UIAlertAction *threeAction = [UIAlertAction actionWithTitle:threeText style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            threeHandler();
        }];
        [alertCtrl addAction:threeAction];
    }
    
    
    

    [vc presentViewController:alertCtrl animated:YES completion:nil];
    
    
}

+ (void)showSheetTitle:(NSString *)title msg:(NSString *)msg cancelTitle:(NSString *)cancelTitle commitBtnTitle:(NSString *)commitText otherBtnTitle:(NSString *)otherTitle cancelHandlerBlock:(void(^)(void))cancelHandel commitHandlerBlock:(void (^)(void))Commithandler otherHandlerBlock:(void(^)(void))otherHandler onVC:(UIViewController *)vc{
    
   
    UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        cancelHandel();
    }];
    [alertCtrl addAction:cancelAction];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:commitText style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        Commithandler();
    }];
    [alertCtrl addAction:sureAction];
    
    
    
    if (otherTitle == nil) {
        
    }else{
        UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            otherHandler();
        }];
        [alertCtrl addAction:otherAction];
    }
    
    
    [vc presentViewController:alertCtrl animated:YES completion:nil];
    
}
+(void)setCoustomObject:(id)object withKey:(NSString *)key{
    NSError *error;
    [[NSUserDefaults standardUserDefaults] setValue:[NSKeyedArchiver archivedDataWithRootObject:object requiringSecureCoding:NO error:&error] forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
+(id)getCoustomObjectWithKey:(NSString *)key{
    return [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] valueForKey:key]];
}

+ (NSString *)getId:(NSString *)Id DicDataWithKey:(NSString *)key {
    NSArray *ary = [[NSUserDefaults standardUserDefaults] valueForKey:key];
    for (NSDictionary *dic in ary) {
        if ([Id isEqualToString:dic[@"value"]]) {
            return dic[@"label"];
        }
    }
    return @"-";
}

+ (NSString *)toolWithHireMode:(NSString *)hireMode {
    if ([hireMode intValue] == 1) {
        return @"周";
    }
    return @"月";
}
+ (NSString *)toolWithAscription:(NSString *)ascription {
    if ([ascription intValue] == 1) {
        return @"企业";
    }
    return @"个人";
}
+ (NSString *)toolWithHireTimeType:(NSInteger )hireTimeType {
    if (hireTimeType == 1) {
        return @"三个月";
    }
    if (hireTimeType == 2) {
        return @"六个月";
    }
    if (hireTimeType == 3) {
        return @"一年";
    }
    return @"-";
}
/**
 转换万元
 */
+ (NSString *)toolWithConversion_W:(NSString *)str {
    
    
    if ([str doubleValue]>1000) {
        str = [[self notRounding:[str doubleValue]/10000 afterPoint:2] stringByAppendingString:@"万元"];
    }
    else {
        str = [[self stringChangeMoneyWithStr:str] stringByAppendingString:@"元"];
    }
    
    return str;
}
+ (NSString *)stringChangeMoneyWithStr:(NSString *)vaule {
    
    // 判断是否null 若是赋值为0 防止崩溃
    if (StringIsEmpty(vaule)) {
        return @"0.00";
    }
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
    [formatter setPositiveFormat:@"###.00"];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    NSString *money = [formatter stringFromNumber:[NSNumber numberWithDouble:[vaule doubleValue]]];
    if ([money hasPrefix:@"."]) return [@"0" stringByAppendingString:money];
    return money;
}
// 精确度
+ (NSString *)stringWithDecimalNumber:(double)num {
    return [[self decimalNumber:num] stringValue];
}
+ (NSDecimalNumber *)decimalNumber:(double)num {
    NSString *numString = [NSString stringWithFormat:@"%lf", num];
    return [NSDecimalNumber decimalNumberWithString:numString];
}


@end
